<?php

namespace app\modules\Cost\controllers;

use Yii;
use app\modules\Cost\models\Cost;
use app\modules\Cost\models\CostSearch;
use app\modules\Product\models\Product;
use app\modules\Product\models\ProductSearch;
use app\modules\Supplier\models\Supplier;
use yii\data\Pagination;
use yii\data\ArrayDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * 成本项管理
 */
class CostController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    //团队列表
    public function actionIndex()
    {

        $searchModel = new ProductSearch();
        $list = $searchModel->search_oper(Yii::$app->request->queryParams);
        
        $lists = [];
        $user_id = \yii::$app->user->id;
        if($list){
            foreach($list as $mod){
                if($mod->oper_id){
                    if(in_array($user_id,json_decode($mod->oper_id))){
                        $lists[] = $mod;
                    }
                }
            }
        }

        $dataProvider = new ArrayDataProvider([
              'allModels' => $lists,
              // 'sort' => [ 
              //     'attributes' => ['go_time', 'day', 'min_price'],
              //     'defaultOrder' => $sort_order,
              // ],
              'pagination' => [
                  'pageSize' => 20,
                  'defaultPageSize'=>20,
              ],
        ]);
     
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);

    }

    //成本项列表
    public function actionList()
    {

        $searchModel = new CostSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);

    }

    //确认成本项
    public function actionConfirm($id){


        $model = $this->findModel($id);
        $payment_time = \yii::$app->request->get('payment_time');
        $model->payment_time = $payment_time;
        $model->confirm = 2;
        $model->comfirm_id = \Yii::$app->user->id;
        $model->comfirm_at = date("Y-m-d H:i:s");
        if($model->save()){
            return $this->redirect(Yii::$app->request->getReferrer());
        }else{
             throw new NotFoundHttpException(Yii::t('app', '确认失败'));   
        }
        
        
    }
    

    //团组成本项
    public function actionCost($product_id)
    {
        $product = Product::findOne($product_id);

        return $this->render('cost',['product'=>$product]);

    }

    //团组报销单文件详情
    public function actionDetail($product_id)
    {
        $model = Product::findOne($product_id);

        return $this->render('detail',['model'=>$model]);
    }



    //查看详情
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    //创建成本项
    public function actionCreate($product_id)
    {   

        $this->layout = '//empty';

        $model = new Cost();

        if ($model->load(Yii::$app->request->post())) {
            $supplier = Supplier::findOne($model->supplier_id);
            if($supplier){
                $model->supplier_type = $supplier->type;
                if($model->supplier_type != 1){
                    $model->day_num = 0;
                }
            }
            if($model->save()){
               
                return $this->redirect(Yii::$app->request->getReferrer());
            }
        }else{
            $model->product_id = $product_id;
            $model->cost_type = 1;
            $model->payment = 1;
            return $this->render('create', [
                'model' => $model,
            ]);
        }

        
    }
    public function actionValidateForm () {

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $model = new Cost();   //这里要替换成自己的模型类
        $model->load(Yii::$app->request->post());  
        return \yii\widgets\ActiveForm::validate($model);  
    }


    //更新成本项
    public function actionUpdate($id)
    {
        $this->layout = '//empty';

        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            $supplier = Supplier::findOne($model->supplier_id);
            if($supplier){
                $model->supplier_type = $supplier->type;
                if($model->supplier_type != 1){
                    $model->day_num = 0;
                }
            }
            if($model->save()){
                return $this->redirect(Yii::$app->request->getReferrer());
            }
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    //获取供应商类型
    public function actionSupplierType($id){
        $model = Supplier::findOne($id);
        if($model){
            return $model->type;
        }else{
            return 0;
        }
    }

    //删除成本项
    public function actionDel($id){

        $model = $this->findModel($id);

        if($model){
            if($model->user_id != \yii::$app->user->id){
                print_r(json_encode(['code'=>0,'message'=>'没有权限删除!']));
                return false;
            }
            $model->status = 2;
            if($model->save()){
                print_r(json_encode(['code'=>1,'message'=>'删除成功!']));
                return false;
            }
        }
        print_r(json_encode(['code'=>0,'message'=>'成本项不存在!']));
        
    }
    

    //下载附件
    public function actionDownload($id){

        $model = $this->findModel($id);
        $name = $model->file_name;
        $url = $model->file_path;
        
        $url = iconv("utf-8","gb2312",$url); 
        if(file_exists($url)){
            header("Content-type: application/octet-stream");    
            header("Accept-Ranges: bytes");    
            header("Accept-Length: " . filesize($url));    
            header("Content-Disposition: attachment; filename=" .$name);    
            @readfile($url);
        }else{
            return false;
        } 

    }      


    protected function findModel($id)
    {
        if (($model = Cost::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }
    
}
